﻿using B.S.AuthCenter.Api.Write.Application.Command.RoleMenu;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Write.Application.Handler.RoleMenu
{
    public class AddRoleMenuHandler : IRequestHandler<AddRoleMenuCommand, ApiResult<int>>
    {
        IBaseRepository<RoleMenuModel> roleMenuRepo;
        IBaseRepository<RoleModel> roleRepo;
        IBaseRepository<MenuManageModel> menuRepo;
        public AddRoleMenuHandler(IBaseRepository<RoleMenuModel> roleMenuRepo, IBaseRepository<RoleModel> roleRepo, IBaseRepository<MenuManageModel> menuRepo)
        {
            this.roleMenuRepo = roleMenuRepo;
            this.roleRepo = roleRepo;
            this.menuRepo = menuRepo;
        }

        public async Task<ApiResult<int>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var rolemenu = roleMenuRepo.GetAll().Where(c => c.Rid == request.Rid).ToList();
            foreach(var item in rolemenu)
            {
                item.IsDeleted=true;
                await roleMenuRepo.Update(item);
            }
            var list=request.Mid.Split(',').Select(x=>Convert.ToInt32(x)).ToList();
            foreach(var item in list)
            {
                RoleMenuModel model = new RoleMenuModel()
                {
                    Rid=request.Rid,
                    Mid=item,
                };
                await roleMenuRepo.Add(model);
            }
            res.Code = ApiEnum.Success;
            res.Data= list;
            res.Msg = "分配权限成功";
            return res;
        }
    }
}
